const express = require("express");
const app = express();
const router = express.Router();

const { mysql , executeQuery } = require("../../mysql");
// 查询全校学生
router.get("/select-student" , async (req , res) =>{
    
    try {

        const { page, size , name = "" , } = req.query;  
        const pageNumber = parseInt(page) || 1;
        const pageSize = parseInt(size) || 20;
        const offset = (pageNumber - 1) * pageSize;


        console.log("student_name===",name);


        let selectQuery = `SELECT * FROM tb_student`;

        // 查询学生的总数
        let countQuery = `SELECT COUNT(*) as total FROM tb_student`;

        // 如果 name 存在且不为空，添加 WHERE 子句来过滤名字
        if (name && name.trim() !== '') {
            selectQuery += ` WHERE student_name LIKE ?`;
        }

        // 分页查询学生的人数
        selectQuery += ` LIMIT ?, ?`;

        // 构建参数数组，注意根据 name 的存在与否来动态添加参数
        let queryParams = [offset , pageSize];

        if (name && name.trim() !== '') {
            queryParams.unshift(`%${name}%`);  // 在数组开头添加名字的模糊匹配条件

            countQuery = `SELECT COUNT(*) AS total FROM tb_student WHERE student_name LIKE '%${name}%';`
        }

        // 查询学生的总数
        // const countQuery = `SELECT COUNT(*) as total FROM tb_student`;

        console.log(selectQuery , queryParams);

        // 查询学生的总数
        const countStutent =  await executeQuery(countQuery);

        console.log(countStutent);

        const totalStudents = countStutent[0].total; // 获取学生总人数

        const totalPages = Math.ceil(totalStudents / pageSize);  // 总页数

        const students = await executeQuery(selectQuery, queryParams);
        
        if(countStutent){

            const response = {
                students: students,
                page: pageNumber,
                size: pageSize,
                totalPages: totalPages,
                totalStudents: totalStudents,
                success : true,
                status : 200,
            };

            res.status(200).json(response);

        }

    } catch (error) {
        
        res.status(500).json(error)
    }

})

module.exports = router;


